//var mysql = require('./../public/javascripts/database.js');
//var timestamp = require('./timestamp.js');

var game = require('./game.js');
var GAMESTATES = {PLACINGPHASE: 0, PLAYER1MOVE: 1, PLAYER2MOVE: 2, PLAYER1WIN: 3, PLAYER2WIN: 4};
var gameInstance;
var databaseInterface = require('./../public/javascripts/SQLQueries.js');
var serverTesting = require('./UnitTests-server.js');

var errorHandler = function (err, req, res) {

    res.render(req.path == '/' ? "home" : req.path.substring(1), {message: "Error: Connection to database unsuccessful", colour: 'red'});
    console.log("[" + timestamp.timeStamp() + "] Error: " + err.stack);

};

function isMobile(req) {

    var ua = req.headers['user-agent'];

    return /mobile/i.test(ua);
}

// Renders device specific home page
exports.home = function (req, res) {

    var link = 'home';

    if (isMobile(req)) {

        link = 'home-mobile';
    }

    if (req.session.username != null) {

        res.render(link, { title: 'Battleships AR', user: req.session.username });
    }
    else {

        res.render(link, { title: 'Battleships AR' });
    }
};

exports.register = function (req, res) {

    res.render('register');

};

exports.admin = function (req, res) {

    if (req.session.admin == true) {

        res.render('admin', { user: req.session.username});

    }

    else {

        res.redirect('/');

    }
};

// Renders page only for users whom have logged in
exports.user = function (req, res) {

    if (typeof req.session.username == 'undefined') {

        res.redirect('/');
    }

    else {

        if (req.session.admin) {

            res.redirect('admin');

        } else {

            var link = 'user';

            if (isMobile(req)) {

                link = 'user-mobile';
            }

            res.render(link, {username: req.session.username});

        }
    }
};

// Registers a new user account in the database
exports.processRegister = function (req, res) {

    var isDuplicate = databaseInterface.checkDuplicateUser(req, res, req.body.username, function(response) {

    if (response === true) {

        res.render("register", {message: "user name: " + req.body.username + " is already in use", colour: 'red'});

    } else {

        databaseInterface.insertUser(req, res, req.body.username, req.body.password, req.body.email);

        res.render("register", {message: "user registered", colour: 'green'});

        }
    });
};

// Handler for login form submitted from homepage
exports.login = function (req, res) {

    databaseInterface.login(req, res, req.body.username, req.body.password, function (response) {

        if (response === "user") {

            res.redirect('/users');

        } else if (response === "admin") {

            res.redirect('/admin');

        } else if (response === "logged in") {

            res.render("home", {message: "Sorry, that account is already logged in....", colour: 'red'});

        } else if (response === "incorrect input") {

            res.render("home", {message: "Incorrect user name or password", colour: 'red'});

        }
    });
};

// Handler for user logout and home page redirect
exports.logout = function (req, res) {

    databaseInterface.logout(req, res, function (response) {

        if (response === "admin") {

            delete req.session.admin;

        }
    });

    delete req.session.username;

    res.redirect('/');

};

exports.DatabaseLists = function (req, res) {

    switch (req.body.postCommand) {

        case("My details"):

            showMyDetails(req, res);
            break;

        case ("Edit My Details"):

            editMyDetails(req, res);
            break;

        case("Show List of Users"):

            showAllUserDetails(req, res);
            break;

        case("Admin Edit Details"):

            adminEditDetails(req, res);
            break;
    }

    function showMyDetails(req, res) {

        databaseInterface.showMyDetails(req, res, function (response, rows) {

            if (response === "user") {

                res.render('user', {database: rows, username: req.session.username});

            }
            else if (response === "admin") {

                res.render('admin', {database: rows});

            } else if (response === "home") {

                res.render("home", {message: "sorry something went wrong...", colour: 'red'});

            }
        });
    }

    function editMyDetails(req, res) {

        databaseInterface.editMyDetails(req, res, function (response) {

            if (response === "in use") {

                res.render("user", {message: "Sorry, but that user name is already in use, please try another.", colour: 'red', username: req.session.username});

            } else if (response === "successful") {

                res.render('user', {message: "Successfully updated details.", colour: 'green', username: req.session.username});

            }
        });
    }

    function showAllUserDetails(req, res) {

        databaseInterface.showAllUserDetails(req, res, function (response, rows) {

            if (response === "failure") {

                res.render('admin', {message: "something went wrong!", colour: 'red'});

            } else if (response === "successful") {

                res.render("admin", {database: rows});

            }
        });
    }

    function adminEditDetails(req, res) {

        databaseInterface.adminEditUser(req, res, req.body.userName, req.body.password, req.body.editThis, req.body.email, req.body.isOnline, req.body.isAdmin, function (response) {

            if (response === "in use") {

                res.render("admin", {message: "Sorry, but that user name is already in use, please try another.", colour: 'red', username: req.session.username});

            } else if (response === "successful") {

                res.render('admin', {message: "Successfully updated details.", colour: 'green', username: req.session.username});

            }
        });
    }
};

exports.requestGRUsers = function (req, res) {

    if (req.session.admin) {

        res.send({users: databaseInterface.getGameReadyUsers(req, res)});

    } else {

        res.send({ error: "Only an admin may get mobile users" });

    }
};

exports.requestGameStart = function (req, res) {

    if (req.session.admin) {

        if (gameInstance != null) {

            res.send({ error: "Please end existing game before starting a new one" });

        } else {

            gameInstance = new game.Game(req.body.player1, req.body.player2);
            res.send({success: "success"});

        }

    } else {

        res.send({ error: "Only an admin may start a game" });

    }
};

exports.requestGameEnd = function (req, res) {

    if (req.session.admin) {

        if (gameInstance == null) {

            res.send({ error: "There is no game to end" });

        } else {

            gameInstance = null;

        }

    } else {

        res.send({ error: "Only an admin may end a game" });

    }
};

exports.requestGameState = function (req, res) {

    if (gameInstance != null) {

        res.send({ response: JSON.stringify(gameInstance.getBoardState(req.session.username)), state: gameInstance.getGameState() });

    } else {

        res.send({ error: "No game currently in play" });

    }
};

// Places ships
exports.request = function (req, res) {

    if (gameInstance != null) {

        if (gameInstance.getGameState() === GAMESTATES.PLAYER1WIN || gameInstance.getGameState() === GAMESTATES.PLAYER2WIN) {

            res.send({ error: "Stop it, the game is over" });

        } else if (gameInstance.getGameState() === GAMESTATES.PLACINGPHASE) {

            res.send(gameInstance.placeShip(req.session.username, req.body.type, req.body.pivotPoint, req.body.orientation));

        } else {

            res.send(gameInstance.takeShot(req.session.username, req.body.coord));

        }

    } else {

        res.send({ error: "No game currently in play" });

    }
};

exports.FbLogin = function (req, res) {

    databaseInterface.CheckFbUserAdded(req, res, req.user.emails[0].value, function (response) {

        if (response === "false") {

            databaseInterface.AddFbUser(req, res, req.user.displayName, req.user.emails[0].value);

            res.render("home", {message: "Creating Battleships-ar account for you....Please press the button again", colour: 'orange'});

        }

        if (response === "true") {

            databaseInterface.FbLogins(req, res, req.user.displayName, function (response) {

                if (response === "user") {

                    res.redirect('/users');

                } else if (response === "admin") {

                    res.redirect('/admin');

                } else if (response === "logged in") {

                    res.render("home", {message: "Sorry, that account is already logged in....", colour: 'red'});
                }
                else if (response === "incorrect input") {

                    res.render("home", {message: "Incorrect user name or password", colour: 'red'});
                }
            });
        }
    });
};

exports.testing = function (req, res) {

    serverTesting.addTest("addtest() Test", function () {

        return true;

    });

    var tests = serverTesting.getTests();
    var serverTests = tests.tests;
    var callbackTests = tests.callbackTests;
    console.log(callbackTests);
    var testTestData = {};

    for (var test in serverTests) {

        testTestData[test] = serverTests[test].call(req, res);

    }

    var setTestResult = function(index, result){
        testTestData[index] = result;
    };
    for(var test in callbackTests){

        testTestData[test] = null;
        callbackTests[test].call("dummy", req, res, test, setTestResult);

    }

    setTimeout(function(){
        console.log(testTestData);
        res.render('testing', {title: "Unit Tests", tests: testTestData})}, 3000
    );
};














